package cn.escco.ocr.config;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
/*
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v137.network.Network;
import org.openqa.selenium.edge.EdgeDriver;
*/
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.escco.ocr.dto.pa.JybLoadDataParam;
import cn.escco.ocr.service.JybCoreService;
import cn.escco.ocr.util.DataMaker;

@Component
public class MyStartupRunner implements ApplicationRunner {

    private String         loginUrl = "https://wmv3846.com/entrance/login";
    private String         username = "windstorm";
    private String         password = "hdeq98uug";

    @Resource
    private JybCoreService jybCoreService;

    @Value("${fldder.log-path}")
    private String logPath;

    // 每隔5秒执行一次
    @Scheduled(fixedRate = 5000)
    public void executeTaskUsingFixedRate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        System.out.println("Execute task using fixed rate: " + sdf.format(new Date()));
        
        new Thread(() -> {
            readSoccerFile();
        }).start();
        new Thread(() -> {
            readBasketFile();
        }).start();
    }
    
    public synchronized void readSoccerFile() {
        String soccerPath = this.logPath + "responseSoccer.txt";
        readFile(soccerPath, "足球");
    }
    
    public synchronized void readBasketFile() {
        String basketPath = this.logPath + "responseBasket.txt";
        readFile(basketPath, "篮球");
    }

    public void readFile(String filePath, String typeName) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            File logFile = new File(filePath);
            if (!logFile.exists()) {
                System.out.println("Log file not found: " + logFile.getAbsolutePath());
                return;
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(logFile), "GBK"));
            String line;
            List<String> logStrList = new ArrayList<>();
            while ((line = reader.readLine())!= null) {
                if(StringUtils.isNotBlank(line)){
                    logStrList.add(line);
                }
            }
            reader.close();
            logFile.delete();

            for (int i = 0; i < logStrList.size(); i++) {
                String logStr = logStrList.get(i);
                String startWith = "Request Time: ";
                if (!logStr.startsWith( startWith)) {
                    System.out.println("Invalid log line: " + logStr);
                    continue;
                }
                logStr = logStr.substring(startWith.length());

                String timeStamp = sdf.format(new Date(Long.parseLong(logStr)));

                i++;
                logStr = logStrList.get(i);
                startWith = "Response body: ";
                if (!logStr.startsWith( startWith)) {
                    System.out.println("Invalid log line: " + logStr);
                    continue;
                }
                logStr = logStr.substring(startWith.length());
                JSONObject json = JSON.parseObject(logStr);
                JybLoadDataParam jybLoadDataParam = DataMaker.json2Entity(json.getJSONObject("data"), timeStamp, typeName);
                long startTime = System.currentTimeMillis();
                jybCoreService.loadDatas(jybLoadDataParam);
                long endTime = System.currentTimeMillis();
                System.out.println(timeStamp + " 处理用时：" + (endTime-startTime) + "s.  Thread ID:" + Thread.currentThread().getId());
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            //runApi();
            //System.out.println("It's running.123321A");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
    public void runApi() throws Exception {
        System.out.println("It's running.123321");
        EdgeDriver driver = new EdgeDriver();
        driver.get(loginUrl);
        driver.findElement(By.cssSelector("input[placeholder=\"请输入用户名\"]")).sendKeys(username);
        driver.findElement(By.cssSelector("input[placeholder=\"请输入密码\"]")).sendKeys(password);
        driver.findElement(By.xpath("/html/body/div[1]/div[3]/div[1]/div[1]/div[last()]")).click();

        Thread.sleep(10000l);

        driver.findElement(
                        By.xpath("/html/body/div[3]/div[6]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[2]"))
                .click();
        Thread.sleep(600l);
        driver.findElement(
                        By.xpath("/html/body/div[3]/div[6]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[2]"))
                .click();
        Thread.sleep(600l);
        driver.findElement(By.xpath("//ul[1]//li[1]//img[1]")).click();

        Thread.sleep(15000l);
        WebElement frame = driver.findElement(By.xpath("//iframe[1]"));

        String iframeUrl = frame.getAttribute("src");
        driver.get(iframeUrl);
        Thread.sleep(10000l);
        driver.findElement(By.xpath("//div[@class='match-type-wrap']/ul[1]/li[4]/span[1]")).click();

        DevTools devTools = driver.getDevTools();

        devTools.createSession();
        devTools.send(Network.enable(Optional.of(1024 * 1024), Optional.of(1024 * 1024), Optional.of(1024 * 1024)));
        devTools.addListener(Network.responseReceived(), responseReceived -> {
            try {
                if (responseReceived.getResponse().getUrl().endsWith("/v1/match/getList")) {
                    System.out.println("Received AJAX response: " + responseReceived.getResponse().getUrl());
                    System.out.println("Response: " + responseReceived.getResponse());
                    Network.GetResponseBodyResponse response = devTools
                            .send(Network.getResponseBody(responseReceived.getRequestId()));
                    String body = response.getBody();
                    JSONObject json = JSON.parseObject(body);
                    JybLoadDataParam jybLoadDataParam = DataMaker.json2Entity(json.getJSONObject("data"));
                    jybCoreService.loadDatas(jybLoadDataParam);
                    System.out.println("Data loaded.");
                }

            } catch (Exception e) {
                System.out.println("Error processing response: " + e.getClass() + e.getMessage());
            }
        });
        devTools.addListener(Network.requestWillBeSent(), requestWillBeSent -> {
            try {
                System.out.println("Received data: " + requestWillBeSent.getDocumentURL());
            } catch (Exception e) {
                System.out.println("Error processing response: " + e.getMessage());
            }
        });
        while (true) {
        }
    }
    */
}
